################################################################################
# Board: MKS Robin Nano v1.1 (Flying Bear Reborn 2.0) / MKS Robin Nano v1.3 / MKS Robin Nano-S v1.3
# Printer: Flying Bear Ghost 4S / Ghost 5 / Reborn
# G-code Macros by ODUCCEU
################################################################################
# WARNING! DO NOT EDIT THIS FILE!
# To override settings from this file, you can copy and paste the relevant
# sections into your printer.cfg and change it there.
################################################################################

# Filament Change ##############################################################

[gcode_macro FILAMENT_CHANGE]
# Unloads filament, waites 5 minutes for manual filament switch and loads again
gcode:
    SAVE_GCODE_STATE NAME=FILAMENT_CHANGE_STATE
    {% set timer = params.T|default(300)|float %}
    {% set unload = params.U|default(100)|float %}
    {% set load = params.L|default(100)|float %}
    {% if printer.pause_resume.is_paused %}
        M118 Already paused
    {% else %}
        {% if printer.toolhead.homed_axes != "xyz" %}
            M118 Homing
            G28                                                                 # home if not homed
        {% else %}
            M118 Pausing print
            PAUSE
        {% endif %}
    {% endif %}
    M118 Changing filament...
    SET_IDLE_TIMEOUT TIMEOUT=7200
    FILAMENT_UNLOAD U={unload}
    COUNTDOWN TIME={timer} MSG="Change filament! Time left: "
    FILAMENT_LOAD L={load}
    RESTORE_GCODE_STATE NAME=FILAMENT_CHANGE_STATE

[gcode_macro LOW_TEMP_CHECK]
gcode:
    {% set extruder_temp = params.T|default(220)|float %}
    {% if printer.extruder.target > extruder_temp %}                            # check for a setpoint for extruder
        {% set extruder_temp = printer.extruder.target %}
    {% endif %}
    {% if printer.extruder.temperature < extruder_temp %}                       # heat to the target temp
        M118 Heating to {extruder_temp}
        SET_HEATER_TEMPERATURE HEATER=extruder TARGET={extruder_temp}
        TEMPERATURE_WAIT SENSOR=extruder MINIMUM={extruder_temp-5}
    {% endif %}

[gcode_macro COUNTDOWN]
gcode: 
    {% set timer = params.TIME|default(10)|int %}
    {% set message = params.MSG|default("Time: ") %}
    # countdown
    {% if timer > 60 %}
        {% for s in range(timer, 60, -10) %}
            M118 {message} {s}s
            G4 P10000                                                           # wait 10 seconds
        {% endfor %}
        {% set timer = 60 %}
    {% endif %}
    {% if timer > 10 %}
        {% for s in range(timer, 10, -5) %}
            M118 {message} {s}s
            G4 P5000                                                            # wait 5 seconds
        {% endfor %}
        {% set timer = 10 %}
    {% endif %}
    {% if timer > 0 %}
        {% for s in range(timer, 0, -1) %}
            M118 {message} {s}s
            G4 P1000                                                            # wait 1 second
        {% endfor %}
    {% endif %}
    #BEEP

[gcode_macro LOAD_FILAMENT]
variable_length1: 2300 # -30mm of length
variable_length2: 2410 # -30mm of length
gcode:
    {% set extruder_temp = params.T|default(220)|float %}
    {% set extruder_num = printer.save_variables.variables.currentextruder|default(1)|int %}
    {% set extruder_lengths = [length1, length2] %}
    {% set dont_move_to_the_nozzle = params.DONTMOVETOTHENOZZLE|default(0)|int %}
    {% set resume_after = params.RESUMEAFTER|default(0)|int %}
    {% set move_clear_after = params.MOVECLEARAFTER|default(0)|int %}
    {% set E = printer["gcode_macro START_PRINT"].retract|float %}
    {% set printingstate = printer["gcode_macro START_PRINT"].printingstate|int %}
    
    {% if printer["filament_switch_sensor extruder_sensor"].filament_detected %}
      M118 Filament already present, loading to the nozzle
      #{% if printer.idle_timeout.state | string == "Printing" and not printer.pause_resume.is_paused and printingstate %} # "Idle", "Printing", "Ready"
        #MMU_ADJUST_CURRENT TOOL={extruder_num}
        #LOW_TEMP_CHECK T={extruder_temp}
      #{% endif %}
      LOW_TEMP_CHECK T={extruder_temp}
      M83                                                                         # relative extrusion
      G0 E100 F600
      M400 # wait all moves
      M118 Filament loaded
      MMU_ADJUST_CURRENT TOOL={extruder_num}
      {% if move_clear_after %}
        G4 P1000 # Wait 1000 to normalize pressure
        G1 E{-E} F2100
        G0 X475 F9000
      {% endif %}
    {% else %}
      {% if printer.extruder.target < extruder_temp %}                       # heat to the target temp
        M118 Heating to {extruder_temp}
        SET_HEATER_TEMPERATURE HEATER=extruder TARGET={extruder_temp}
      {% endif %}

      #MMU_LOAD_TOOL TOOL={extruder_num} LENGTH={extruder_lengths[extruder_num-1]}
      MMU_LOAD_TOOL TOOL={extruder_num} EXTRALENGTH=9 HOMINGLENGTH=3000
      _LOAD_FILAMENT_STAGE2 T={extruder_temp} DONTMOVETOTHENOZZLE={dont_move_to_the_nozzle} RESUMEAFTER={resume_after} MOVECLEARAFTER={move_clear_after}
    {% endif %}

[delayed_gcode DELAYED_ADJUST_CURRENT]
gcode:
    {% set extruder_num = printer.save_variables.variables.currentextruder|default(1)|int %}
    UPDATE_DELAYED_GCODE ID=DELAYED_ADJUST_CURRENT DURATION=0
    MMU_ADJUST_CURRENT TOOL={extruder_num}

[gcode_macro _LOAD_FILAMENT_STAGE2]
variable_isworking: True
gcode:
    {% set extruder_temp = params.T|default(220)|float %}
    {% set extruder_num = printer.save_variables.variables.currentextruder|default(1)|int %}
    {% set dont_move_to_the_nozzle = params.DONTMOVETOTHENOZZLE|default(0)|int %}
    {% set resume_after = params.RESUMEAFTER|default(0)|int %}
    {% set move_clear_after = params.MOVECLEARAFTER|default(0)|int %}
    {% set E = printer["gcode_macro START_PRINT"].retract|float %}
    {% set printingstate = printer["gcode_macro START_PRINT"].printingstate|int %}
    {% if printer["filament_switch_sensor extruder_sensor"].filament_detected %}
      {% if printer.idle_timeout.state | string == "Printing" and printer.pause_resume.is_paused and dont_move_to_the_nozzle %}
        # Set delayed current setting as it needs to move to the nozzle
        UPDATE_DELAYED_GCODE ID=DELAYED_ADJUST_CURRENT DURATION=60
        {% if resume_after %}
          RESUME
        {% endif %}
      {% else %}
        LOW_TEMP_CHECK T={extruder_temp}
        #G0 E78 F600
        M83                                                                         # relative extrusion
        G0 E100 F600
        M400 # wait all moves
        M118 Filament loaded
        MMU_ADJUST_CURRENT TOOL={extruder_num}
        {% if move_clear_after %}
          G4 P1000 # Wait 1000 to normalize pressure
          G1 E{-E} F2100
          G0 X475 F9000
          SET_GCODE_VARIABLE MACRO=START_PRINT VARIABLE=printingstate VALUE=1
        {% endif %}
        {% if resume_after %}
          RESUME
        {% endif %}
      {% endif %}
    {% else %}
      MMU_MOTORS_OFF
      #BEEP
      M400 # wait all moves
      M118 Load filament error
      SET_HEATER_TEMPERATURE HEATER=extruder TARGET=0
      {% if printer.idle_timeout.state | string == "Printing" and not printer.pause_resume.is_paused and printingstate %} # "Idle", "Printing", "Ready"
        PAUSE
      {% endif %}
    {% endif %}

[gcode_macro SYNC_EXTRUDER]
gcode:
    {% set extruder_num = printer.save_variables.variables.currentextruder|default(1)|int %}
    MMU_SYNC_TOOL TOOL={extruder_num}
    {% for e in range(1, 3, 1) %}
      {% if extruder_num == e %}
        SET_GCODE_VARIABLE MACRO=T{e} VARIABLE=active VALUE=1
      {% else %}
        SET_GCODE_VARIABLE MACRO=T{e} VARIABLE=active VALUE=0
      {% endif %}
    {% endfor %}
    M118 Tool {extruder_num} is selected

[gcode_macro _SET_ACTIVE_TOOL]
gcode:
    {% set extruder_num = params.TOOL|default(1)|int %}
    {% if printer["filament_switch_sensor extruder_sensor"].filament_detected %}
      M118 Filament already present, can't switch tool
    {% else %}
      SAVE_VARIABLE VARIABLE=currentextruder VALUE={extruder_num}
      SYNC_EXTRUDER
    {% endif %}

[gcode_macro T1]
variable_active: 0
variable_color: "00ff00"
gcode:
    _SET_ACTIVE_TOOL TOOL=1

[gcode_macro T2]
variable_active: 0
variable_color: "ff0000"
gcode:
    _SET_ACTIVE_TOOL TOOL=2

[gcode_macro UNLOAD_FILAMENT]
gcode:
    {% set extruder_lengths = [printer["gcode_macro LOAD_FILAMENT"].length1, printer["gcode_macro LOAD_FILAMENT"].length2] %}
    {% set extruder_temp = params.T|default(220)|float %}
    {% set extruder_num = printer.save_variables.variables.currentextruder|default(1)|int %}
    M83                                                                         # relative extrusion
    {% if printer["filament_switch_sensor extruder_sensor"].filament_detected %}
      M118 Filament present
      {% if extruder_temp > 0 %}
        LOW_TEMP_CHECK T={extruder_temp}
      {% endif %}
      #SET_FILAMENT_SENSOR SENSOR=extruder_sensor ENABLE=0
      #{% for e in range(1, 3, 1) %}
      #  {% if extruder_num == e %}
      #    SYNC_EXTRUDER_MOTION EXTRUDER=extr{e} MOTION_QUEUE=extruder
      #  {% else %}
      #    SYNC_EXTRUDER_MOTION EXTRUDER=extr{e} MOTION_QUEUE=
      #  {% endif %}
      #{% endfor %}
      SET_HEATER_TEMPERATURE HEATER=extruder TARGET=0
      #G0 E10 F1000                                                                 # push back the filament to smash any stringing 
      SET_GCODE_VARIABLE MACRO=START_PRINT VARIABLE=printingstate VALUE=0
      G0 E-5 F600                                                                # extract filament to the coldend zone 
      G4 P3000                                                                    # wait for 3 seconds
      #G0 E5 F500                                                                 # push back the filament to smash any stringing 
      G0 E-70 F600 # Move just after extruder feeder
      #M400
    {% endif %}
    MMU_ADJUST_CURRENT TOOL=0
    MMU_UNLOAD_TOOL TOOL={extruder_num} LENGTH={extruder_lengths[extruder_num-1]}
      
    #SYNC_EXTRUDER_MOTION EXTRUDER=extruder MOTION_QUEUE=
    #{% if extruder_num == 1 %}
    #  MMU_SYNC_SELECTOR_MOTOR SYNC=0
    #{% else %}
    #  MMU_SYNC_GEAR_MOTOR SYNC=0 SERVO=0
    #{% endif %}
    
    #MMU_SYNC_TOOL TOOL=0
    
    #G0 E-{extruder_lengths[extruder_num-1]} F6000
    
    #{% if extruder_num == 1 %}
    #  MMU_MOVE_SELECTOR LENGTH=-{extruder_lengths[extruder_num-1]} SPEED=200
    #{% else %}
    #  _MMU_STEP_LOAD_BOWDEN LENGTH=-{extruder_lengths[extruder_num-1]}
    #{% endif %}
    
    #M400
    #SET_FILAMENT_SENSOR SENSOR=extruder_sensor ENABLE=1
    #M84 E
    #{% for e in range(1, 3, 1) %}
      #SYNC_EXTRUDER_MOTION EXTRUDER=extr{e} MOTION_QUEUE=
      #SET_STEPPER_ENABLE STEPPER=extr{e} ENABLE=0
    #{% endfor %}
    #SET_STEPPER_ENABLE STEPPER="extruder_stepper extr{extruder_num}" ENABLE=0
    MMU_MOTORS_OFF
    #SYNC_EXTRUDER_MOTION EXTRUDER=extruder MOTION_QUEUE=extruder
    #{% if extruder_num == 1 %}
    #  MMU_SYNC_SELECTOR_MOTOR SYNC=1
    #{% else %}
    #  MMU_SYNC_GEAR_MOTOR SYNC=1 SERVO=0
    #{% endif %}
    
    #MMU_SYNC_TOOL TOOL={extruder_num}
    M118 Filament unloaded

[delayed_gcode Sync_active_extruder]
initial_duration: 1
gcode:
    # Sync active extruder in case filament sensor triggered
    #{% set currentextruder = printer.save_variables.variables.currentextruder|default(1)|int %}
    #{% if printer["filament_switch_sensor filament_sensor"].filament_detected %}
    #  SYNC_EXTRUDER_MOTION EXTRUDER=extr{currentextruder} MOTION_QUEUE=extruder
    #{% endif %}
    SYNC_EXTRUDER
    
################################################################################
